package com.weixin.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

public class FileUtil {

	private static String tmpFileName = "temp.txt";

	public static List<String> readFile() {
		return readFile(tmpFileName);
	}

	public static void clearFile(String fileName) {
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile(fileName, "rw");
			FileChannel fc = rf.getChannel();
			// 将文件大小截为0
			fc.truncate(0);
			rf.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rf != null) {
				try {
					rf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static List<String> readFileFromFullPath(String fileName) {
		List<String> list = new ArrayList<String>();
		BufferedReader br = null;
		File f = null;
		try {

			org.springframework.core.io.Resource fileRource = new ClassPathResource(
					fileName);
			f = new File(fileRource.getURI());
			br = new BufferedReader(new FileReader(f));
			
			String line = null;
			while ((line = br.readLine()) != null) {
				if (StringUtils.isNotBlank(line)) {
					list.add(line);
					// 将文本打印到控制台
					System.out.println(line);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			
			// 关闭BufferedReader
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		return list;
	}
	
	
	public static List<String> readFile(String fileName) {
		System.out
				.println("**********************read start*************************");
		List<String> list = new ArrayList<String>();
		BufferedReader br = null;
		try {

			/*org.springframework.core.io.Resource fileRource = new ClassPathResource(
					fileName);*/
			String fileRoot = FileUtil.class.getClassLoader().getResource("").getPath();
			String filePath = fileRoot+ fileName;
			File file = new File(filePath);
			
			
			br = new BufferedReader(new InputStreamReader(
					new FileInputStream(file)));

			String line = null;
			while ((line = br.readLine()) != null) {
				if (StringUtils.isNotBlank(line)) {
					list.add(line);
					// 将文本打印到控制台
					System.out.println(line);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭BufferedReader
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out
				.println("**********************read end*************************");
		return list;
	}
	
	public static String readFileFromProperties(String key){
		List<String> result = readFileFromFullPath("lbs.properties");
		String resultValue = "";
		if(result!=null && result.size()>0){
			for (String value : result) {
				if(value.contains("=")){
					String keyValue = value.split("=")[1];
					String _key = value.split("=")[0];
					if(_key.trim().equals(key.trim())){
						resultValue = keyValue;
						break;
					}
				}
			}
		}
		return resultValue;
	}
	

	public static void writeFile(List<String> contentList) throws IOException {
		
		if(contentList !=null && contentList.size()>0){
			String filePath = getFilePath();
			File file = new File(filePath);// 指定要写入的文件
			if (!file.exists()) {// 如果文件不存在则创建
				file.createNewFile();
			}
			// 获取该文件的缓冲输出流
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
			// 写入信息
			for (String cont : contentList) {
				bufferedWriter.write(cont);
			}
			bufferedWriter.flush();// 清空缓冲区
			bufferedWriter.close();// 关闭输出流
		}
	}
	
	 public static void appendWrite(String content) {   
		 appendWrite(tmpFileName,Arrays.asList(content));
	 }

	
	 public static void appendWrite(String fileName, List<String> conList) {  
		 	String fileRoot = FileUtil.class.getClassLoader().getResource("").getPath();
		 	File rootFile = new File(fileRoot);
			String filePath = fileRoot+ fileName;
			File file = new File(filePath);
			
			if(!rootFile.exists()){
				rootFile.mkdirs();
			}
			
			if(!file.exists()){
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		 
	        RandomAccessFile randomFile = null;  
	        try {     
	        	if(conList !=null && conList.size()>0){
	        		// 打开一个随机访问文件流，按读写方式     
	        		randomFile = new RandomAccessFile(filePath, "rw");     
	        		// 文件长度，字节数     
	        		long fileLength = randomFile.length();     
	        		for (String cnt : conList) {
			            // 将写文件指针移到文件尾。     
			            randomFile.seek(fileLength);   
			            
			            String _cnt = cnt+"\n";
			            randomFile.write(_cnt.getBytes()); 
			            
			            fileLength += _cnt.getBytes().length;
					}
	        		  
	        	}
	            
	        } catch (IOException e) {     
	            e.printStackTrace();     
	        } finally{  
	            if(randomFile != null){  
	                try { 
	                    randomFile.close();  
	                } catch (IOException e) {  
	                    e.printStackTrace();  
	                }  
	            }  
	        }  
	    }    
	 
	public static String getFilePath() {
		String fileRoot = FileUtil.class.getClassLoader().getResource("").getPath();
		String filePath = fileRoot+ tmpFileName;
		return filePath;
	}

	public static void main(String[] args) {
		@SuppressWarnings("rawtypes")
		List list = FileUtil.readFile("lbs.properties");
		for (Object obj : list) {
			//System.out.println(obj);
		}
		try {
			//writeFile(Arrays.asList(new String[]{"4","333"}));
			//clearFile(getFilePath());
			System.out.println(FileUtil.readFileFromProperties("L1.MSIDS"));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			appendWrite("t666.txt",Arrays.asList(new String[]{"测试","333"}));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
